/*********************************************************
*Copyright (c) 2009 Rob Groves. All Rights in All
*@des: 异步并发TCP Sever
*@name: Async_Server.hpp
*@author: zhogn17hao
*@time: 2016-03-24
*********************************************************/

#ifndef __ASYNC_SERVER_HPP__
#define __ASYNC_SERVER_HPP__

#include <iostream>
#include <boost/asio.hpp>
#include <boost/bind.hpp>  
#include <boost/noncopyable.hpp>
#include <boost/asio/spawn.hpp>
#include <boost/make_shared.hpp>
#include <boost/shared_ptr.hpp>
#include <boost/function.hpp>

#include "session.hpp"

class async_server : public boost::noncopyable
{
public:
	//typedef boost::shared_ptr<boost::asio::io_service> io_service_sptr;
	//typedef boost::shared_ptr<boost::asio::io_service::work> work_sptr;
    async_server(boost::asio::io_service& ios, short port): ios_(ios), port_(port){

    }

    void run(){
    	state = 1; //设置服务器状态 开启
    	//使用boost::coroutine
		boost::asio::spawn(ios_, 
			[&](boost::asio::yield_context yield){
				boost::asio::ip::tcp::acceptor acceptor(ios_,
        			boost::asio::ip::tcp::endpoint(boost::asio::ip::tcp::v4(), port_));
				while(state){
					boost::system::error_code ec;
					auto new_session = boost::make_shared<session>(ios_);        
        			acceptor.async_accept(new_session->socket(), yield[ec]);
        			if (!ec){
                        new_session->set_cb_read_msg(cb_read_msg);
            			new_session->run();
        			}
				}
			}
		);
		//boost::bind(async_server::do_accept, this, boost::asio::placeholders::_1));
		ios_.run();
    }

    void stop(){
    	state = 0; //设置服务器状态 关闭
    }

    void set_cb_read_msg(session::CALLBACK_READ_MSG cb_){
        cb_read_msg = cb_;
    }
private:
	int state; //服务器状态 开启 关闭

	boost::asio::io_service& ios_;
	short port_;
    //连接管理
    //std::shared_ptr<session_manager> m_pManager;
    //
    session::CALLBACK_READ_MSG cb_read_msg;
};

#endif //__ASYNC_SERVER_HPP__


